//
//  MCMallStatisticsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/4/25.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCMallStatisticsViewController: MCViewController {
    
    var pageNumber = 1
    
    private var beginTimeStr = ""    // 开始时间
    private var endTimeStr = ""      // 结束时间
    
    private var clerkId = 0          // 店员Id


    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        pageNumber = 1
        sendNetworking_getOrderList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetwork_getClerk()
    }
    

    
    // MARK: - Network
    
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var clerkArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()

    
    lazy var headView: MCMallStatisticsHeaderView = {
        let view = MCMallStatisticsHeaderView()
        view.beginTimeButton.addTarget(self, action: #selector(beginTimeButtonClicked), for: .touchUpInside)
        view.endTimeButton.addTarget(self, action: #selector(endTimeButtonClicked), for: .touchUpInside)
        view.sureButotn.addTarget(self, action: #selector(sureButtonClicked), for: .touchUpInside)
        
        
        view.popUpChooseView.closure = { model in
            view.chooseButton.nameLabel.text = model.nickName
            self.clerkId = model.clerkId
        }

        return view
    }()
    
    lazy var popUpBeginDateView: MCDatePickerPopupView = {
        let view = MCDatePickerPopupView()
        view.cancelButton.backgroundColor = UIColor.MCBlue
        view.sureButton.backgroundColor = UIColor.MCBlue

        view.pickerView.maximumDate = Date.init()
        view.pickerView.datePickerClosure = { timeStr in
            self.headView.beginTimeButton.nameLabel.text = timeStr
            
            self.beginTimeStr = timeStr
        }
        
        view.pickerView.settingPickerView(mode: MCDateMode.year_month_day)
        
        return view
    }()
    
    
    lazy var popUpEndDateView: MCDatePickerPopupView = {
        let view = MCDatePickerPopupView()
        view.cancelButton.backgroundColor = UIColor.MCBlue
        view.sureButton.backgroundColor = UIColor.MCBlue
        
        view.pickerView.maximumDate = Date.init()
        view.pickerView.datePickerClosure = { timeStr in
            self.headView.endTimeButton.nameLabel.text = timeStr
            self.endTimeStr = timeStr
        }
        
        
        return view
    }()
    
}

//MARK: 通知回调，闭包回调，点击事件
extension MCMallStatisticsViewController {
    @objc func rightItemClicked() {
        let vc = MCOrderSearchViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func beginTimeButtonClicked() {
        
        headView.endTimeButton.nameLabel.text = "选择结束时间"
        
        view.window?.addSubview(popUpBeginDateView)
        popUpBeginDateView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    @objc func endTimeButtonClicked() {
        
        popUpEndDateView.pickerView.minimumDate = MCDateManager_getDateFromString(beginTimeStr)
        popUpEndDateView.pickerView.settingPickerView(mode: MCDateMode.year_month_day)
        view.window?.addSubview(popUpEndDateView)
        popUpEndDateView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    @objc func sureButtonClicked() {
        pageNumber = 1
        sendNetworking_getOrderList()
    }
}


//MARK: 网络请求
extension MCMallStatisticsViewController {

    func sendNetworking_getOrderList() {
        let para = [
            "storeId"   : MCUserinfo_getStoreId(),
            "pageNum"   : pageNumber,
            "startTime" : beginTimeStr,
            "endTime"   : endTimeStr,
            "clerkId"   : clerkId
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_mallStoreOrderStatistics, para, vc: self, success: { (data) in

            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
                self.tableView.mj_footer.resetNoMoreData()
            }
            
            let dataDict = data.dictionaryObject ?? [:]
            
            self.headView.dataDict = dataDict
            
            let array = dataDict["list"] as? NSArray ?? []
            
            if array.count + self.dataArrayM.count == 0 {
                self.headView.isShowEmptyView = true
            } else {
                self.headView.isShowEmptyView = false
                
                if array.count == 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                
                for dict in array {
                    let fatherModel = MCOrderListFatherModel()
                    fatherModel.setValuesForKeys(dict as! [String : Any])
                    self.dataArrayM.add(fatherModel)
                }
            }
            self.tableView.reloadData()
            
        }, failure: nil)
        
    }
    
    // 获取员工数据
    func sendNetwork_getClerk() {
        let para = [
            "pageNum" : pageNumber,
            "pageSize": 10000
            ] as [String : Any]
        
        
        MCNetwork.POST(JAVA_getClerkList, para, vc: self, success: { (data) in
            
            let dataArray = data.arrayObject ?? []
            
            self.clerkArrayM.removeAllObjects()
            
            for dict in dataArray {
                let model = MCClerkManageModel()
                model.setValuesForKeys(dict as? [String:Any] ?? [:])
                self.clerkArrayM.add(model)
            }
            
            let allModel = MCClerkManageModel()
            allModel.nickName = "全部"
            allModel.clerkId = 0
            self.clerkArrayM.insert(allModel, at: 0)
            
            
            self.headView.popUpChooseView.dataArrayM = self.clerkArrayM
            self.headView.popUpChooseView.tableView.reloadData()
        }, failure: nil)
    }
}

//MARK: UI的处理,通知的接收
extension MCMallStatisticsViewController {
    func baseSetting() {
        self.title = "订单统计"
        self.view.backgroundColor = UIColor.white
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_search"), target: self, selector: #selector(rightItemClicked))
        
        
        
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking_getOrderList()
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking_getOrderList()
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, MCSafeAreaBottomHeight, 0))
        }
        
        tableView.tableHeaderView = headView
    }

}



extension MCMallStatisticsViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let model = self.dataArrayM[section] as! MCOrderListFatherModel
        
        let view = MCOrderListSectionHeaderView()
        
        view.model = model
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let model = self.dataArrayM[section] as! MCOrderListFatherModel
        
        let view = MCMallStatisticsSectionFooterView()
        view.model = model

        return view
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let model = self.dataArrayM[section] as! MCOrderListFatherModel
        
        return model.listBaOrderDetailVo.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 132
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel
        
        let cell = MCMallStatisticsCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        cell.model = model.listBaOrderDetailVo[indexPath.row] as! MCOrderListModel
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel
        
        
        let vc = MCOrderDetailShowViewController()
        vc.orderSn = model.orderSn
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}



